<template>
  <el-dialog
    v-model="visible"
    title="上传POC模板 (ZIP)"
    width="600px"
    :close-on-click-modal="false"
  >
    <div class="upload-content">
      <el-upload
        ref="uploadRef"
        class="upload-dragger"
        drag
        :auto-upload="false"
        :on-change="handleFileChange"
        :on-remove="handleFileRemove"
        :file-list="fileList"
        accept=".zip"
        :limit="1"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          将ZIP文件拖到此处，或<em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">只能上传ZIP文件</div>
        </template>
      </el-upload>

      <div class="upload-options">
        <el-checkbox v-model="options.auto_extract">自动解压</el-checkbox>
        <el-checkbox v-model="options.sync_to_scanner"
          >同步到扫描器</el-checkbox
        >
      </div>

      <div v-if="uploadResult" class="upload-result">
        <el-alert
          :title="uploadResult.title"
          :type="uploadResult.type"
          :closable="false"
          show-icon
        >
          <div v-if="uploadResult.data">
            <p>总文件数: {{ uploadResult.data.total_files }}</p>
            <p>导入成功: {{ uploadResult.data.imported }}</p>
            <p v-if="uploadResult.data.failed > 0">
              失败: {{ uploadResult.data.failed }}
            </p>
            <p v-if="uploadResult.data.failed_files?.length">
              失败文件: {{ uploadResult.data.failed_files.join(", ") }}
            </p>
            <p v-if="uploadResult.data.sync_status">
              {{ uploadResult.data.sync_status }}
            </p>
          </div>
        </el-alert>
      </div>
    </div>

    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <el-button
        type="primary"
        @click="handleSubmit"
        :loading="uploading"
        :disabled="fileList.length === 0"
      >
        确认上传
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from "vue";
import { ElMessage } from "element-plus";
import { UploadFilled } from "@element-plus/icons-vue";
import type { UploadFile, UploadFiles } from "element-plus";
import { uploadPocZip } from "../../../servers";

// 定义props
const props = defineProps({
  modelValue: { type: Boolean, default: false },
});

// 定义emits
const emit = defineEmits<{
  (e: "update:modelValue", value: boolean): void;
  (e: "uploaded"): void;
}>();

// visible computed 属性
const visible = computed({
  get: () => props.modelValue,
  set: (value: boolean) => emit("update:modelValue", value),
});

const uploading = ref(false);
const uploadRef = ref();
const fileList = ref<UploadFiles>([]);
const options = ref({
  auto_extract: true,
  sync_to_scanner: false,
});
const uploadResult = ref<any>(null);

// 文件变化
const handleFileChange = (file: UploadFile) => {
  uploadResult.value = null;
  if (file.raw) {
    const isZip =
      file.raw.type === "application/zip" || file.name.endsWith(".zip");
    if (!isZip) {
      ElMessage.error("只能上传ZIP文件");
      fileList.value = [];
      return;
    }
  }
};

// 文件移除
const handleFileRemove = () => {
  uploadResult.value = null;
};

// 提交上传
const handleSubmit = async () => {
  if (fileList.value.length === 0) {
    ElMessage.warning("请先选择要上传的文件");
    return;
  }

  uploading.value = true;
  try {
    const file = fileList.value[0].raw;
    if (!file) {
      ElMessage.error("文件不存在");
      return;
    }

    const formData = new FormData();
    formData.append("file", file);
    formData.append("sync_to_scanner", String(options.value.sync_to_scanner));

    const result = await uploadPocZip(formData);

    if (result.code === 2000) {
      uploadResult.value = {
        title: "上传成功",
        type: "success",
        data: result.data,
      };
      ElMessage.success(result.message || "上传成功");
      // 延迟关闭，让用户看到结果
      setTimeout(() => {
        handleCancel();
        emit("uploaded");
      }, 2000);
    } else {
      uploadResult.value = {
        title: "上传失败",
        type: "error",
      };
      ElMessage.error(result.message || "上传失败");
    }
  } catch (error: any) {
    ElMessage.error(error?.message || "上传失败");
    uploadResult.value = {
      title: "上传失败",
      type: "error",
    };
  } finally {
    uploading.value = false;
  }
};

// 取消
const handleCancel = () => {
  // 重置状态
  fileList.value = [];
  uploadResult.value = null;
  options.value = {
    auto_extract: true,
    sync_to_scanner: false,
  };
  emit("update:modelValue", false);
};

// 监听弹窗关闭，重置状态
watch(
  () => props.modelValue,
  (newVal) => {
    if (!newVal) {
      fileList.value = [];
      uploadResult.value = null;
    }
  }
);
</script>

<style scoped lang="scss">
.upload-content {
  min-height: 300px;
}

.upload-dragger {
  width: 100%;
  margin-bottom: 20px;

  :deep(.el-upload-dragger) {
    width: 100%;
    height: 180px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }

  .el-icon--upload {
    font-size: 67px;
    color: #c0c4cc;
    margin-bottom: 16px;
  }

  .el-upload__text {
    color: #606266;
    font-size: 14px;
    text-align: center;

    em {
      color: #409eff;
      font-style: normal;
    }
  }

  .el-upload__tip {
    color: #909399;
    font-size: 12px;
    margin-top: 7px;
    text-align: center;
  }
}

.upload-options {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.upload-result {
  margin-top: 20px;
}
</style>
